import commands

import openpyxl
import os

import shutil

from common.Tools import get_patch_from_code, find_real_git_path, handle_patch_file

# CONFIG_XLS_FILE_PATH = "./../tableExport.xlsx"
CONFIG_XLS_FILE_PATH = "/home/android/Opensource/WorkSpace_Py/PatchTools/tableExport.xlsx"

# CONFIG_XLS_REPO_PREFIX = "platform/"
CONFIG_XLS_REPO_PREFIX = ["alps/", "platform/"]

CONFIG_ORI_CODE_PATH = "/home/android/Platform/mtk132"

# CONFIG_TEMP_PATCH_PATH = "/home/android/Opensource/WorkSpace_Py/MtkSecurityToolPy27/patch"
CONFIG_TEMP_PATCH_PATH = "/home/android/Platform/p200_pan/generate_patch"

# CONFIG_DST_CODE_PATH = "/home/android/Platform/Platform_p130_1/android"
# CONFIG_DST_CODE_PATH = "/home/android/Platform/p130_gms/android"
CONFIG_DST_CODE_PATH = "/home/android/Platform/p200_pan/android"

CONFIG_JIRA_ID = "PCAAO-1924"

if __name__ == '__main__':
    wb = None
    try:
        wb = openpyxl.load_workbook(filename=CONFIG_XLS_FILE_PATH, read_only=False)
    except Exception as e:
        print("open %s failed" % CONFIG_XLS_FILE_PATH, e)
        exit(-1)
    sheet_name = wb.sheetnames[0]
    print("sheet name %s" % sheet_name)
    sheet = wb[sheet_name]

    # Included
    Included_list = sheet['A']

    Work_list = []
    total_work = 0
    sub_index_list = []
    for index in range(len(Included_list)):
        is_None = False
        if Included_list[index].value is None:
            # print("None index[%s]" % index)
            is_None = True
            sub_index_list.append(index)
        else:
            is_None = False
            sub_index_list.append(index)
            if Included_list[index].value == "No":
                # print("Need patch row index %s" % index)
                total_work = total_work + 1
                Work_list.append({total_work: sub_index_list[:]})
            else:
                pass
            # print("sub_index_list:", sub_index_list)
            sub_index_list = []

    print("Work_list:", Work_list)

    if os.path.exists(CONFIG_TEMP_PATCH_PATH):
        shutil.rmtree(CONFIG_TEMP_PATCH_PATH)

    get_patch_success_count = 0
    get_patch_failed_count = 0

    git_apply_success_count = 0
    git_apply_failed_count = 0

    for index in range(1, len(Work_list)):
        print("+++++++++++++++++++++++++++++++++++++++++")
        work = Work_list[index]
        detail_work = work[index + 1]
        base_index = detail_work[0]
        Patch_ID = ("%s" % sheet["C%s" % base_index].value).strip()
        Title = ("%s" % sheet["D%s" % base_index].value).strip()
        base_Repo_Name = sheet["F%s" % base_index].value
        print("Patch_ID: %s" % Patch_ID)
        print("Title: %s" % Title)
        for sub_index in range(len(detail_work)):
            sub_work_index = detail_work[sub_index]
            Repo_Name = sheet["F%s" % sub_work_index].value
            if Repo_Name is None:
                Repo_Name = base_Repo_Name
            Sorted_Commits = sheet["G%s" % sub_work_index].value
            print("    Repo_Name: %s" % Repo_Name)
            print("    Sorted_Commits: %s" % Sorted_Commits)

            for prefix in CONFIG_XLS_REPO_PREFIX:
                if Repo_Name.startswith(prefix):
                    fix_repo_name = Repo_Name[len(prefix):]
                    print("    fix_repo_name: %s prefix: %s" % (fix_repo_name, prefix))
                    break

            ret, dst_patch_path = get_patch_from_code(CONFIG_ORI_CODE_PATH, fix_repo_name, Sorted_Commits,
                                                      CONFIG_TEMP_PATCH_PATH)
            if ret == 0:
                dst_git_path = find_real_git_path(CONFIG_DST_CODE_PATH, fix_repo_name)
                if dst_git_path is not None:
                    dst_repo_name = dst_git_path[len(CONFIG_DST_CODE_PATH) + 1:]
                    subject_title, _diff_info = handle_patch_file(dst_git_path, dst_patch_path, fix_repo_name,
                                                                  dst_repo_name)

                    os_cmd_apply = "cd %s; git apply %s" % (dst_git_path, dst_patch_path + "bk")

                    print("apply cmd", os_cmd_apply)
                    print("dst_git_path", dst_git_path)
                    print("dst_patch_path", dst_patch_path + "bk")
                    print("subject_title", subject_title)
                    print("jira id", CONFIG_JIRA_ID)

                    apply_status, apply_info = commands.getstatusoutput(os_cmd_apply)
                    if apply_status == 0:
                        commit_str = "\'<REQ><%s><%s>\'" % (CONFIG_JIRA_ID, subject_title[len("Subject: "):])
                        os_cmd_commit = "cd %s; git add -A .; git commit -m %s" % (dst_git_path, commit_str)
                        print("os_cmd_commit=" + os_cmd_commit)
                        commit_status, commit_info = commands.getstatusoutput(os_cmd_commit)
                        if commit_status == 0:
                            git_apply_success_count = git_apply_success_count + 1
                        else:
                            git_apply_failed_count = git_apply_failed_count + 1
                            print("\033[43;31;1mcommit failed error commit_status=%s info=%s\033[0m" % (
                                commit_status, commit_info))
                    else:
                        print("\033[43;31;1mapply failed error apply_status=%s info=%s\033[0m" % (
                            apply_status, apply_info))
                        git_apply_failed_count = git_apply_failed_count + 1
                    # try:
                    #     ret_apply = subprocess.check_call(execute_cmd)
                    #     print("git apply success ret=%s" % ret_apply)
                    #     git_apply_success_count = git_apply_success_count + 1
                    # except Exception as e:
                    #     git_apply_failed_count = git_apply_failed_count + 1
                    #     print("git apply failed", e)

                    get_patch_success_count = get_patch_success_count + 1
            else:
                print("\033[43;31;1mget_patch_from_code error ret=%s fix_repo_name=%s\033[0m" % (ret, fix_repo_name))
                get_patch_failed_count = get_patch_failed_count + 1
        print("------------------------------------------")

    print("total=%s get_patch_success_count=%s get_patch_failed_count=%s" % (
        (get_patch_success_count + get_patch_failed_count), get_patch_success_count, get_patch_failed_count))

    print("git apply success=%s failed=%s" % (git_apply_success_count, git_apply_failed_count))
